//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by 孙明海 on 16/1/27.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import Foundation
import SDWebImage

/// 微博数据列表模型
class StatusListViewModel {
    lazy var statusList = [StatusViewModel]()
    
    func loadStatus(ispullup: Bool,finished: (isSuccessed: Bool) -> ()) {
        
        let since_id = ispullup ? 0 : (statusList.first?.status.id ?? 0)
        let max_id = ispullup ? (statusList.last?.status.id ?? 0) : 0
        
        StatusDAL.loadStatus(since_id, max_id: max_id) { (array) -> () in
            
            guard let array = array else {
                finished(isSuccessed: false)
                return
            }
            
            var arrayM = [StatusViewModel]()
            for dict in array {
                arrayM.append(StatusViewModel(status: Status(dict: dict)))
            }
            if max_id > 0 {
                self.statusList += arrayM
            } else {
                
                self.statusList = arrayM + self.statusList
            }
//            self.cacheSingleImage(arrayM, finished: finished)
            self.cacheSingleImage(arrayM,finished: finished)
        }
    }
    
    /// 缓存单张图片, 在刷新数据之前确保单独已经全部缓存到本地了,这样就可以设置单图的布局
    private func cacheSingleImage(statusList: [StatusViewModel], finished: (isSuccessed: Bool) -> ()) {
        let group = dispatch_group_create()
        
        var dataLenght = 0
        for vm in statusList {
            if vm.thumbnailUrls?.count != 1 {
                continue
            }
            
            let url = vm.thumbnailUrls![0]
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(url,
                options: [],
                progress: nil,
                completed: { (image, _, _, _, _) -> Void in
                    if let image = image, let data = UIImagePNGRepresentation(image) {
                        dataLenght += data.length
                    }
                    dispatch_group_leave(group)
            })
            
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存 \(dataLenght / 1024) k")
            finished(isSuccessed: true)
        }
    }
    
}